﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Excel_2010_Measure_Reader
{
    public partial class Main : Form
    {
        private FileMeasureSetList _lastResults;

        private readonly string _noResultsMessage = @"No measures were read." 
                        + Environment.NewLine + @"You must check-off individual file nodes or right-double-click a directory node to launch the Check Options dialog."
                        + Environment.NewLine + @"Once file nodes have been selected, then click the 'Read Measures' button for results.";

        private FileMeasureSetList LastResults
        {
            get 
            {
                if (_lastResults == null)
                {
                    _lastResults = new FileMeasureSetList();
                }
                return _lastResults; 
            }

            set { _lastResults = value; } 
        }

        public Main()
        {
            InitializeComponent();
        }

        private void readButton_Click(object sender, EventArgs e)
        {
            LastResults.Clear();

            try
            {
                var fileMeasuresList = ExcelFiles.ReadAllMeasures(directoryTree);

                if (fileMeasuresList.Count == 0)
                {
                    txtResults.Text = _noResultsMessage; 
                }
                else
                {
                    var sb = new StringBuilder(string.Empty);

                    foreach (var fileMeasures in fileMeasuresList)
                    {
                        sb.AppendLine("File: " + fileMeasures.FileName);
                        sb.AppendLine("Path: " + fileMeasures.DirectoryName);
                        sb.AppendLine();

                        if (fileMeasures.Measures.Count == 0)
                        {
                            sb.AppendLine("Unable to extract measures from file");

                            if (!string.IsNullOrEmpty(fileMeasures.ErrorMessage))
                            {
                                sb.AppendLine("Error Message: " + fileMeasures.ErrorMessage);
                            }
                        }
                        else
                        {
                            foreach (var measure in fileMeasures.Measures)
                            {
                                sb.AppendLine(measure);
                            }
                        }
                        sb.AppendLine();
                    }
                    txtResults.Text = sb.ToString();
                }

                LastResults = fileMeasuresList;
            }
            catch (ExcelException ex)
            {
                txtResults.Text = @"An error occurrd which stopped processing of measures. " 
                    + @"The error message gave the following information: "  
                    + ex.Message + Environment.NewLine 
                    + @"Stack Trace: " + Environment.NewLine
                    + ex.StackTrace;
            }

            tabControl.SelectTab(pgResults);
            txtResults.Focus();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            directoryTree.ReadDrives();
            CenterToScreen();
            directoryTree.Select();
        }


        private void closeButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void tabControl_Selected(object sender, TabControlEventArgs e)
        {
            readButton.Enabled = (e.TabPage == pgSelect);
            saveResultsButton.Enabled = !readButton.Enabled;
            listUniqueMeasuresButton.Enabled = saveResultsButton.Enabled && LastResults.Count > 0;

            if (e.TabPage == pgResults && string.IsNullOrEmpty(txtResults.Text.Trim()))
            {
                txtResults.Text = _noResultsMessage;
            }
            
        }

        private void saveResultsButton_Click(object sender, EventArgs e)
        {
            saveFileDialog.DefaultExt = "txt";
            saveFileDialog.FileName = "Results.txt";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(saveFileDialog.FileName, txtResults.Text);
            }
        }

        private void listUniqueMeasuresButton_Click(object sender, EventArgs e)
        {
            var measures = new List<string>();

            if (LastResults.Count > 0)
            {
                var sb = new StringBuilder(string.Empty);

                foreach (var fileMeasureSet in LastResults)
                {
                    if (fileMeasureSet.Measures.Count > 0)
                    {
                        foreach (var measure in fileMeasureSet.Measures)
                        {
                            if (!measures.Contains(measure + ";"))
                            {
                                measures.Add(measure + ";");
                            }
                        }   
                    }
                }

                var sortedMeasures = measures.AsEnumerable().OrderBy(measure => measure.ToUpper()).Select(measure => measure);

                foreach (var measure in sortedMeasures)
                {
                    sb.AppendLine(measure);    
                }
                
                txtResults.Text = sb.ToString();
                txtResults.Select();
            }
        }

        private void txtResults_KeyDown(object sender, KeyEventArgs e)
        {  
            if (e.Control && e.KeyCode == Keys.A)
            {
                var control = sender as TextBox;

                if (control != null)
                {
                    control.SelectAll();
                }
            }
        }
    }
}